<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>音频文件管理器 - 神算子</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
        }

        .header h1 {
            color: #333;
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            color: #666;
            font-size: 1.1em;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 15px;
            text-align: center;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }

        .stat-card h3 {
            font-size: 0.9em;
            margin-bottom: 10px;
            opacity: 0.9;
        }

        .stat-card .value {
            font-size: 2em;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .stat-card .unit {
            font-size: 0.8em;
            opacity: 0.8;
        }

        .actions {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            margin-bottom: 30px;
        }

        .action-btn {
            padding: 15px 25px;
            border: none;
            border-radius: 10px;
            font-size: 1em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-danger {
            background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
            color: white;
        }

        .btn-warning {
            background: linear-gradient(135deg, #feca57 0%, #ff9ff3 100%);
            color: white;
        }

        .btn-success {
            background: linear-gradient(135deg, #48dbfb 0%, #0abde3 100%);
            color: white;
        }

        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
        }

        .action-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .log-container {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #e9ecef;
        }

        .log-entry {
            padding: 8px 12px;
            margin-bottom: 5px;
            border-radius: 5px;
            font-family: 'Courier New', monospace;
            font-size: 0.9em;
        }

        .log-entry.info {
            background: #d1ecf1;
            color: #0c5460;
            border-left: 4px solid #17a2b8;
        }

        .log-entry.success {
            background: #d4edda;
            color: #155724;
            border-left: 4px solid #28a745;
        }

        .log-entry.error {
            background: #f8d7da;
            color: #721c24;
            border-left: 4px solid #dc3545;
        }

        .log-entry.warning {
            background: #fff3cd;
            color: #856404;
            border-left: 4px solid #ffc107;
        }

        .auto-cleanup-status {
            background: #e9ecef;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
        }

        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-running {
            background: #28a745;
            animation: pulse 2s infinite;
        }

        .status-stopped {
            background: #dc3545;
        }

        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }

        .refresh-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            font-size: 1.5em;
            cursor: pointer;
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
        }

        .refresh-btn:hover {
            transform: scale(1.1);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎵 音频文件管理器</h1>
            <p>管理和清理音频文件，优化存储空间</p>
        </div>

        <div class="auto-cleanup-status">
            <span class="status-indicator" id="statusIndicator"></span>
            <span id="statusText">检查自动清理状态中...</span>
        </div>

        <div class="stats-grid">
            <div class="stat-card">
                <h3>总文件数</h3>
                <div class="value" id="totalFiles">-</div>
                <div class="unit">个文件</div>
            </div>
            <div class="stat-card">
                <h3>已播放</h3>
                <div class="value" id="playedFiles">-</div>
                <div class="unit">个文件</div>
            </div>
            <div class="stat-card">
                <h3>未播放</h3>
                <div class="value" id="unplayedFiles">-</div>
                <div class="unit">个文件</div>
            </div>
            <div class="stat-card">
                <h3>总大小</h3>
                <div class="value" id="totalSize">-</div>
                <div class="unit">MB</div>
            </div>
        </div>

        <div class="actions">
            <button class="action-btn btn-primary" onclick="refreshStats()">🔄 刷新统计</button>
            <button class="action-btn btn-danger" onclick="cleanupAll()">🧹 清理所有</button>
            <button class="action-btn btn-warning" onclick="cleanupPlayed()">🗑️ 清理已播放</button>
            <button class="action-btn btn-success" onclick="cleanupOld()">⏰ 清理过期</button>
            <button class="action-btn btn-primary" id="autoCleanupBtn" onclick="toggleAutoCleanup()">⚙️ 自动清理</button>
        </div>

        <div class="log-container">
            <h3 style="margin-bottom: 15px; color: #333;">📋 操作日志</h3>
            <div id="logContainer">
                <div class="log-entry info">[系统] 音频文件管理器已加载</div>
            </div>
        </div>
    </div>

    <button class="refresh-btn" onclick="refreshStats()" title="刷新统计信息">
        🔄
    </button>

    <script>
        let autoCleanupRunning = false;

        // 添加日志条目
        function addLog(message, type = 'info') {
            const logContainer = document.getElementById('logContainer');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry ${type}`;
            logEntry.textContent = `[${timestamp}] ${message}`;
            
            logContainer.insertBefore(logEntry, logContainer.firstChild);
            
            // 限制日志条目数量
            if (logContainer.children.length > 50) {
                logContainer.removeChild(logContainer.lastChild);
            }
        }

        // 刷新统计信息
        async function refreshStats() {
            try {
                addLog('正在刷新统计信息...', 'info');
                
                const response = await fetch('/audio/stats');
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                
                const stats = await response.json();
                
                document.getElementById('totalFiles').textContent = stats.total_files;
                document.getElementById('playedFiles').textContent = stats.played_files;
                document.getElementById('unplayedFiles').textContent = stats.unplayed_files;
                document.getElementById('totalSize').textContent = stats.total_size_mb;
                
                addLog(`统计信息已更新: 总计${stats.total_files}个文件，${stats.total_size_mb}MB`, 'success');
                
            } catch (error) {
                addLog(`刷新统计信息失败: ${error.message}`, 'error');
            }
        }

        // 清理所有文件
        async function cleanupAll() {
            if (!confirm('确定要清理所有已播放和过期的音频文件吗？')) {
                return;
            }
            
            try {
                addLog('开始清理所有文件...', 'info');
                
                const response = await fetch('/audio/cleanup', {
                    method: 'POST'
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                
                const result = await response.json();
                addLog(`清理完成: 删除${result.total_deleted}个文件 (已播放:${result.played_files_deleted}, 过期:${result.old_files_deleted})`, 'success');
                
                // 刷新统计信息
                await refreshStats();
                
            } catch (error) {
                addLog(`清理失败: ${error.message}`, 'error');
            }
        }

        // 清理已播放文件
        async function cleanupPlayed() {
            if (!confirm('确定要清理所有已播放的音频文件吗？')) {
                return;
            }
            
            try {
                addLog('开始清理已播放文件...', 'info');
                
                const response = await fetch('/audio/cleanup-played', {
                    method: 'DELETE'
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                
                const result = await response.json();
                addLog(`清理已播放文件完成: 删除${result.deleted_count}个文件`, 'success');
                
                // 刷新统计信息
                await refreshStats();
                
            } catch (error) {
                addLog(`清理已播放文件失败: ${error.message}`, 'error');
            }
        }

        // 清理过期文件
        async function cleanupOld() {
            if (!confirm('确定要清理所有过期的音频文件吗？')) {
                return;
            }
            
            try {
                addLog('开始清理过期文件...', 'info');
                
                const response = await fetch('/audio/cleanup-old', {
                    method: 'DELETE'
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                
                const result = await response.json();
                addLog(`清理过期文件完成: 删除${result.deleted_count}个文件`, 'success');
                
                // 刷新统计信息
                await refreshStats();
                
            } catch (error) {
                addLog(`清理过期文件失败: ${error.message}`, 'error');
            }
        }

        // 切换自动清理
        async function toggleAutoCleanup() {
            try {
                const endpoint = autoCleanupRunning ? '/audio/auto-cleanup/stop' : '/audio/auto-cleanup/start';
                const action = autoCleanupRunning ? '停止' : '启动';
                
                addLog(`正在${action}自动清理任务...`, 'info');
                
                const response = await fetch(endpoint, {
                    method: 'POST'
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}`);
                }
                
                const result = await response.json();
                autoCleanupRunning = !autoCleanupRunning;
                updateAutoCleanupStatus();
                
                addLog(`自动清理任务${action}成功`, 'success');
                
            } catch (error) {
                addLog(`自动清理任务操作失败: ${error.message}`, 'error');
            }
        }

        // 更新自动清理状态显示
        function updateAutoCleanupStatus() {
            const indicator = document.getElementById('statusIndicator');
            const statusText = document.getElementById('statusText');
            const autoCleanupBtn = document.getElementById('autoCleanupBtn');
            
            if (autoCleanupRunning) {
                indicator.className = 'status-indicator status-running';
                statusText.textContent = '自动清理任务正在运行中 (每5分钟执行一次)';
                autoCleanupBtn.textContent = '🛑 停止自动清理';
            } else {
                indicator.className = 'status-indicator status-stopped';
                statusText.textContent = '自动清理任务已停止';
                autoCleanupBtn.textContent = '▶️ 启动自动清理';
            }
        }

        // 页面加载时初始化
        window.addEventListener('load', async function() {
            addLog('初始化音频文件管理器...', 'info');
            
            // 刷新统计信息
            await refreshStats();
            
            // 假设自动清理默认是启动的（根据main.py中的启动事件）
            autoCleanupRunning = true;
            updateAutoCleanupStatus();
            
            addLog('音频文件管理器初始化完成', 'success');
        });

        // 定期刷新统计信息
        setInterval(refreshStats, 30000); // 每30秒刷新一次
    </script>
</body>
</html>